import Vue from 'vue'
import utils from '../../utils'

/**
 * 计算内容的高度 以显示滚动条
 * 滚动高度条 窗口高度 - 元素距离body的偏移量 - binding.value || 0
 * v-scrollHeight[, ={Number}]
 */

/**
 * global vars
 * 全局变量
 */
let newStyle = 'position: absolute;left: -100%;display: block;visibility: hidden;'

/**
 * win client heiht
 * 获取可视窗口高度
 */
const win = () => {
    return document.documentElement.clientHeight || document.body.clientHeight
}

/**
 * element offset
 * 获取元素偏移量
 */
const getoffset = (el) => {
    let offsetTop = utils.offset(el).top
    // - 如果是三段使用滚动条 单独处理某些问题 根据底部值算出高度
    let layerRtb = utils.getClassParents(el, 'layerRtb')
    if (layerRtb !== document && offsetTop === 0) {
        let oldStyle = layerRtb.getAttribute('style')
        layerRtb.setAttribute('style', newStyle)
        offsetTop = utils.offset(el).top
        layerRtb.setAttribute('style', oldStyle)
    }
    // - 如果是二段板块使用 v-show 时
    let uiTab9Con = utils.getClassParents(el, 'uiTab9Con')
    if (uiTab9Con !== document && offsetTop === 0) {
        let oldStyle = uiTab9Con.getAttribute('style')
        uiTab9Con.setAttribute('style', newStyle)
        offsetTop = utils.offset(el).top
        uiTab9Con.setAttribute('style', oldStyle)
    }
    return offsetTop
}

/**
 * element subtract
 * 获取其他差值
 */
const getsubtract = (el, binding) => {
    let subtract = binding.value || 0
    // - 如果是三段使用滚动条 单独处理某些问题 根据底部值算出高度
    let layerRtb = utils.getClassParents(el, 'layerRtb')
    if (layerRtb !== document) {
        let footerElement = layerRtb.querySelector('.layerRtb-footer')
        if (footerElement) {
            let footerHeight = footerElement.offsetHeight
            if (footerHeight === 0) {
                let oldStyle = layerRtb.getAttribute('style')
                layerRtb.setAttribute('style', newStyle)
                footerHeight = footerElement.offsetHeight
                layerRtb.setAttribute('style', oldStyle)
            }
            subtract = footerHeight || subtract
        }
    }
    return subtract
}

/**
 * set css
 * 设置滚动样式
 */
const setStyle = (el, h) => {
    utils.setCss(el, 'height', h)
    utils.setCss(el, 'overflowY', 'auto')
    utils.setCss(el, 'width', '100%')
    utils.addClass(el, 'thinScroll')
}

export default {
    name: 'scrollHeight',
    bind (el, binding) {
        el.resize = function () {
            setStyle(el, win() - getoffset(el) - getsubtract(el, binding))
        }
        Vue.nextTick(() => {
            el.resize()
        })
        window.addEventListener('resize', () => {
            if (typeof el.resize === 'function') {
                Vue.nextTick(() => {
                    el.resize()
                })
            }
        }, false)
    },
    unbind (el, binding) {
        el.resize = undefined
    },
    componentUpdated (el, binding) {
        if (binding.modifiers.update) {
            setTimeout(() => {
                setStyle(el, win() - getoffset(el) - getsubtract(el, binding))
            })
        }
    }
}
